/**	 
 * @Description 
 * @Path		com.bbx.taxi.client.Activity.Base.BaseBBXActivity.java 
 * @Author		年向   
 * @Date		2015年7月16日 下午3:41:43 
 * @Company	 	蓝海（福建）信息技术有限公司	 
 */
package com.bbx.taxi.client.Activity.Base;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;

import com.bbx.androidapi.util.DensityUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.gclient.Observer;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Activity.Order.OrderCancelReason;
import com.bbx.taxi.client.Activity.Order.OrderEvaluationActivity2;
import com.bbx.taxi.client.Activity.Order.StartServiceActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.Bean.Message.ObserverListener;
import com.bbx.taxi.client.Bean.Message.Publisher;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_TYPE;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_STATUS;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderingDB;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Service.TimeService;
import com.bbx.taxi.client.Task.MyOrderTask;
import com.bbx.taxi.client.Task.MyOrderTask.OnOrderFinishListener;
import com.bbx.taxi.client.Task.MyOrderingTask;
import com.bbx.taxi.client.Task.MyOrderingTask.OnOrderingFinishListener;
import com.bbx.taxi.client.Util.AppStarted;
import com.bbx.taxi.client.Util.ClickFilter;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.widget.Dailog.MessageDialog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyBusyDailog;
import com.bbx.taxi.client.widget.Dailog.MyPayOrderDailog;
import com.bbx.taxi.client.widget.Dailog.MySnTimeOutDialog;
import com.bbx.taxi.client.widget.Dailog.MyTypeDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.client.widget.Dailog.MyPayOrderDailog.onClickPayListener;
import com.bbx.taxi.client.widget.StatusBar.StatusBar;
import com.bbx.taxi.client.widget.SwipeBackLayout;
import com.yanxuwen.loadview.LoadingDialog;
import com.example.mylistview.pullListView.PullToRefreshLayout;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.SwipeMenuCreator;
import com.example.mylistview.swipemenu.SwipeMenuItem;
import com.umeng.analytics.MobclickAgent;

/**
 * @Description
 * @Path com.bbx.taxi.client.Activity.Base.BaseBBXActivity.java
 * @Author 年向
 * @Date 2015年7月16日 下午3:41:43
 * @Company 蓝海（福建）信息技术有限公司
 */
public abstract class BaseBBXActivity extends BbxBaseActivity implements
		ObserverListener, OnOrderingFinishListener, OnOrderFinishListener,
		OnDismissListener {
	public LinearLayout layout_base;
	RelativeLayout ly_content;
	public PullToRefreshLayout  pullToRefreshLayout;
	public MyListView mMyListView;
	public final static int MSG_ORDER_WRITE = 1000;
	public final static int MSG_ORDERING_WRITE = 2000;
	/** false为数据库还没写入完整，true为写入完整【全部订单】 */
	public boolean isWriteFinish = false;
	/** false为数据库还没写入完整，true为写入完整【进行中的订单】 */
	public boolean isWriteIngFinish = false;
	public static int requestCode = 1;
	protected int requestCode2 = 2;
	protected int resultCode = 1;
	protected SwipeBackLayout layout;
	protected Activity context;
	protected RelativeLayout title_comm;
	protected TextView tv_title;
	protected ImageView iv_left;
	protected ImageView iv_right_sub;
	public TextView tv_right;
	protected boolean isObserver = false;
	public boolean IsSwipeBack = true;
	public MyApplication mApplication;
	public LoadingDialog loaddialog;
	/** onResume是否刷新订单 */
	public boolean isRefreshOrder = true;
	//是否开启每分钟监听一次
	public boolean isTime=true;
	public boolean isShowTitle=true;
	public MySnTimeOutDialog mMySnTimeOutDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mApplication = MyApplication.getInstance();
		mApplication.addActivity(this);
		loaddialog=new LoadingDialog(this, Value.LOADDIALOGTIME);
		loaddialog.setOnDismissListener(this);
		context = this;
		ButterKnife.bind(this);
		if (IsSwipeBack) {
			layout = (SwipeBackLayout) LayoutInflater.from(this).inflate(
					R.layout.base, null);
			layout.attachToActivity(this);
		}
		StatusBar.setTranslucentStatus(this,true);
		initTitle();
		iniListView();
		//只监听不做加载
		MyOrderingTask.setOnOrderingFinishListener(this);
		super.onCreate(savedInstanceState);
	}

	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}

	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(R.layout.base_status);
		layout_base = (LinearLayout) findViewById(R.id.layout_base);
		 ly_content = (RelativeLayout) findViewById(R.id.ly_content);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View contentView = inflater.inflate(layoutResID, null);
		LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		contentView.setLayoutParams(layoutParams);
		contentView.setBackgroundDrawable(null);
		if (null != ly_content) {
			ly_content.addView(contentView);
		}
	}
	@Override
	public void initFinished() {
		super.initFinished();
		ly_content.setVisibility(View.VISIBLE);
	}
    private void iniListView(){
    	pullToRefreshLayout=(PullToRefreshLayout)findViewById(R.id.pullToRefreshLayout);
    	mMyListView=(MyListView)findViewById(R.id.MyListView);
    }
	private void initTitle() {
		title_comm=(RelativeLayout)findViewById(R.id.title_comm);
		tv_title = (TextView) findViewById(R.id.tv_title);
		iv_left = (ImageView) findViewById(R.id.iv_left);
		iv_right_sub = (ImageView) findViewById(R.id.iv_right_sub);
		tv_right = (TextView) findViewById(R.id.tv_right);
		if(!isShowTitle){
			title_comm.setVisibility(View.GONE);
		}
	}

	public void setTitle(int titleId) {
		setTitle(true, getString(titleId), -1, null);
	}

	public void setTitle(String title) {
		setTitle(true, title, -1, null);
	}
	/**
	 * 由于有动画，所以不能事先吧布局设置隐藏，在setTitle在显示标题，，这样每个界面都会有显示出来的动画不好看
	 */
	public void showTitle(boolean isShowTitle){
		this.isShowTitle=isShowTitle;
	}
	public void setTitle(boolean isBack, String title, int rightSubId,
			String right) {
		// 左边返回
		if (!isBack) {
			iv_left.setVisibility(View.GONE);
		} else {
			iv_left.setVisibility(View.VISIBLE);
			iv_left.setOnClickListener(this);
			if (iv_left != null) {
				iv_left.setImageResource(R.drawable.btn_back_down);
			}
		}

		// 标题
		if (tv_title != null) {
			tv_title.setText(TextUtils.isEmpty(title) ? getString(R.string.app_name)
					: title);
			tv_title.setOnClickListener(this);
		}

		// 第二按钮
		if (rightSubId != -1) {
			iv_right_sub.setVisibility(View.GONE);
		} else {
			iv_right_sub.setVisibility(View.VISIBLE);
			if (iv_right_sub != null) {
				iv_right_sub.setImageResource(rightSubId);
				iv_right_sub.setOnClickListener(this);
			}
		}

		// 第一菜单
		if (tv_right != null) {
			if (TextUtils.isEmpty(right)) {
				tv_right.setVisibility(View.GONE);
			} else {
				tv_right.setVisibility(View.VISIBLE);
				tv_right.setText(right);
				tv_right.setOnClickListener(this);
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (!ClickFilter.filter())
			return;
		switch (v.getId()) {
		case R.id.iv_left:
			onfinish();
			break;

		default:
			super.onClick(v);
			break;
		}
	}
	/**
	 * 初始化ListView的Item菜单,注意布局必须引用mylistview或者mylistview2
	 */
	public void initswipe() {
		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackgroundColor(getResources().getColor(
						R.color.red));
				// set item width
				openItem.setWidth(DensityUtil.dip2px(context, 65));
				// set item title
//				openItem.setIcon(R.drawable.icon_delete);
				openItem.setTitle(getString(R.string.delete));
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				// // create "delete" item
				// SwipeMenuItem deleteItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				// 0x3F, 0x25)));
				// // set item width
				// deleteItem.setWidth(dp2px(90));
				// // set a icon
				// deleteItem.setIcon(R.drawable.ic_delete);
				// // add to menu
				// menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mMyListView.setMenuCreator(creator);
		mMyListView.setOnSwipeListener(new OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				pullToRefreshLayout.setIsProhibitPull(true);
			}

			@Override
			public void onSwipeEnd(int position) {
				pullToRefreshLayout.setIsProhibitPull(false);
			}
		});

	}
	@Override
	public void finish() {
		hideSoftInputView();
		super.finish();
		overridePendingTransition(0, R.anim.base_slide_right_out);
		if(isPublisher)
		Publisher.getInstance().removeOb(this);
	}

	public void onfinish() {
		finish();

	}

	@Override
	protected void onAppExit() {
		// TODO Auto-generated method stub

	}

	public void startActivity(Intent intent) {
		super.startActivity(intent);
		try{
		if(intent.getComponent().getPackageName().trim().equals(AppStarted.getAppPackageName(context))){
			overridePendingTransition(R.anim.base_slide_right_in,
					R.anim.base_slide_remain);
			if(isPublisher)
			Publisher.getInstance().removeOb(this);
		}}catch(Exception e){}
	}

	public void startActivityForResult(Intent intent, int code) {
		super.startActivityForResult(intent, code);
		try{
		if(intent.getComponent().getPackageName().trim().equals(AppStarted.getAppPackageName(context))){
		overridePendingTransition(R.anim.base_slide_right_in,
				R.anim.base_slide_remain);
		if(isPublisher)
		Publisher.getInstance().removeOb(this);
		}}catch(Exception e){
			Log.e("",e+"");
		}
	}

	@Override
	protected void onResume() {
		if(isTime){
		   startService(new Intent(context, TimeService.class));
		}
		MobclickAgent.onResume(this);
		if(isPublisher)
		Publisher.getInstance().addOb(this);
		super.onResume();
		if (!Value.isActive) {
			// app 从后台唤醒，进入前台
			Value.isActive = true;
			MyApplication.getInstance().setIsStartUp(true);
			if (Value.isUnSDK) {
				if (mApplication.getUid() != null && !mApplication.equals("")
						&& mApplication.getToken() != null
						&& !mApplication.getToken().equals("")) {
				} else {
					ToastUtil.showToast(context, R.string.account_exception);
					Intent intent = new Intent(this, LoginActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
			if (isRefreshOrder) {
				Value.isActive = true;
				if (mApplication != null) {
					MyOrderingTask.getInstance(context)
							.setOnOrderingFinishListener(this);
					MyOrderTask.getInstance(context).setOnOrderFinishListener(
							this);
				}
			}
		}

	}

	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (!AppStarted.isRunningForeground(this)) {
			// 记录当前已经进入后台app 进入后台
			Value.isActive = false;
		}
	}

	@Override
	protected void desotryItems() {
		isObserver = false;
	}

	/**
	 * 隐藏软键盘
	 */
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager) this
				.getSystemService(Activity.INPUT_METHOD_SERVICE));
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 关闭右滑动退出
	 */
	public void setOnCloseSwipeLayout(boolean isClose) {
		if (layout != null)
			layout.setOnClose(isClose);
	}
	boolean isPublisher=true;
	public void setPublisher(boolean isPublisher){
		this.isPublisher=isPublisher;
	}

	/**
	 * 滚动到起始位置
	 */
	public void onScrollOrigin() {
		if (layout != null)
			layout.scrollOrigin();
	}

	public void onNotify(int type, JSONObject jb, Msgs.Data msgs_data) {
		switch (type) {
		case GMsg.ONLINE_PAIDAN:
			ToastUtil.showToast(context, R.string.msg_paidan);
			break;
		case GMsg.ONLINE_CANCEL:
		case GMsg.ONLINE_KF_CANCEL:
			MessageDialog.onKfCancelDialog(context, msgs_data);
			break;
		case GMsg.ONLINE_GAIPAI:
		case GMsg.ONLINE_KF_GAIPAIL:
		case GMsg.ONLINE_SJ_GAIPAIL: 
			MessageDialog.onGaipaiDialog(context, msgs_data);
			break;
		case GMsg.ONLINE_ONCAR:
			ToastUtil.showToast(context, R.string.msg_oncar);
			break;
		case GMsg.ONLINE_OFFCAR:// 下车
			MessageDialog.onOffCarDialog(context, msgs_data);
			break;
		case GMsg.ONLINE_FINISH:
			// ToastUtil.showToast(context, R.string.msg_finish);
			break;
		case GMsg.ONLINE_BUSY:
			MessageDialog.onBusyDialog(context, msgs_data);
			break;
		case GMsg.ONLINE_RELOGIN:
			MessageDialog.onReloginDialog2(context);
			break;
		case GMsg.ONLINE_ENTER_COUPON:
			MessageDialog.onEnterCouponDialog(context, jb);
			break;
		case GMsg.OFFICAIL_AA:
			MessageDialog.onAADialog(context, msgs_data);
			break;
		case GMsg.ONLINE_SNTIMEOUT:
			mMySnTimeOutDialog=MessageDialog.onSnTimeDialog(context, msgs_data);
			break;
		case GMsg.ONLINE_SNTOQIANGDAN:
			if(msgs_data!=null&&msgs_data.getOrder_id()!=null&&!msgs_data.getOrder_id().equals("")){
				 MessageDialog.onSnQiangDanDialog(context,msgs_data.getOrder_id(),false,null);
			}
			break;
		case GMsg.ONLINE_KF_CHANGE_ORDER:
		case GMsg.ONLINE_KF_CHANGE_PRICE:
		case GMsg.ONLINE_KF_CHANGE_PRICE2:
			MessageDialog.onChangeDialog(context, type,msgs_data);
			MyOrderingTask.getInstance(context).setOnOrderingFinishListener(
					this);
			MyOrderTask.getInstance(context);
			break;
		case GMsg.ONLINE_KF_CHANGE:
			ToastUtil.showToast(context, R.string.toast_change);
			MyOrderingTask.getInstance(context).setOnOrderingFinishListener(
					this);
			MyOrderTask.getInstance(context);
			break;
		}

	}
	@Override
	public void onNotify(int type, Object object) {
	   switch (type) {
		  case GMsg.ONLINE_ACTIVITY:
			MessageDialog.onActivityDialog(context, object,false);
			break;
		  case GMsg.ONLINE_SNQIANGDAN:
			  MessageDialog.onSnQiangDanDialog(context,(String)object,false,null);
			  break;
		}

	}
	public void onNotifyData(ObserverListener.DATA_STATUS data_status,ObserverListener.DATA_TYPE data_type,int status,Object object){
	}
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				hideInput();
			}
			return super.dispatchTouchEvent(ev);
		}
		// 必不可少，否则所有的组件都不会有TouchEvent了
		if (getWindow().superDispatchTouchEvent(ev)) {
			return true;
		}
		return onTouchEvent(ev);
	}

	public boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null && (v instanceof EditText)) {
			int[] leftTop = { 0, 0 };
			// 获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
			int top = leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if (event.getX() > left && event.getX() < right
					&& event.getY() > top && event.getY() < bottom) {
				// 点击的是输入框区域，保留点击EditText的事件
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	/**
	 * 强制隐藏键盘
	 */
	public void hideInput() {
		try {
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					View v = getCurrentFocus();
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					if(imm!=null&&v!=null&&v.getWindowToken()!=null)
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			}, 0);
		} catch (Exception e) {
		}
	}

	/**
	 * 显示软键盘
	 */
	public void showInput() {
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				View v = getCurrentFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
			}
		}, 0);

	}

	@Override
	public void onOrderingFinish(ArrayList<MyOrderList> list) {
	}

	@Override
	public void onOrderFinish(ArrayList<MyOrderList> list) {
	}

	/**
	 * 存储数据库完成
	 */
	public Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_ORDER_WRITE:
				isWriteFinish = true;
				break;
			case MSG_ORDERING_WRITE:
				isWriteIngFinish = true;
				break;
			}
		};
	};

	protected void onDestroy() {
		MyOrderingTask.removeOnOrderingFinishListener(this);
		MyOrderTask.removeOnOrderFinishListener(this);
		if (loaddialog != null) {
			loaddialog.dismiss();
			loaddialog = null;
		}
		super.onDestroy();
	};

	/**
	 * 加载框消息监听
	 */
	@Override
	public void onDismiss(DialogInterface dialog) {
		// TODO Auto-generated method stub

	}
}
